package com.nlp.visualization.core.discourse.impl;

import com.kennycason.kumo.CollisionMode;
import com.kennycason.kumo.WordCloud;
import com.kennycason.kumo.WordFrequency;
import com.kennycason.kumo.bg.CircleBackground;
import com.kennycason.kumo.bg.PixelBoundryBackground;
import com.kennycason.kumo.bg.RectangleBackground;
import com.kennycason.kumo.font.KumoFont;
import com.kennycason.kumo.font.scale.LinearFontScalar;
import com.kennycason.kumo.font.scale.SqrtFontScalar;
import com.kennycason.kumo.nlp.FrequencyAnalyzer;
import com.kennycason.kumo.nlp.filter.UrlFilter;
import com.kennycason.kumo.nlp.normalize.TrimToEmptyNormalizer;
import com.kennycason.kumo.nlp.tokenizers.ChineseWordTokenizer;
import com.kennycason.kumo.palette.ColorPalette;
import com.kennycason.kumo.palette.LinearGradientColorPalette;

import com.nlp.visualization.core.discourse.IWordsCloudService;
import com.nlp.visualization.core.seg.filter.SegFilter;
import com.nlp.visualization.pojo.NLP.discourse.WordsCloudOption;
import com.nlp.visualization.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Service
public class WordsCloudServiceImpl implements IWordsCloudService {


    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

    Logger logger = LoggerFactory.getLogger(WordsCloudServiceImpl.class);

    private int fontScaleFrom = 10;
    private int fontScanleTo = 45;
    //    private String defaultFont="STHeiti Light";
    private int defaultFontSize = 10;


    /**
     * 圆形的
     *
     * @param texts
     * @param option
     * @return
     * @throws IOException
     */
    @Override
    public File CicleCloud(List texts, WordsCloudOption option) throws IOException {
//
        logger.info("为text:" + texts.get(0).toString().substring(0, texts.get(0).toString().length() / 10) + "..." + "生成圆形词云");
        final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
        final UrlFilter urlFilter = new UrlFilter();
        final String filePath = getFileSavePath(option.getSavePath());

        frequencyAnalyzer.setWordFrequenciesToReturn(600);
        //设置最小分词长度为
        frequencyAnalyzer.setMinWordLength(option.getMinWordLength());
        //过滤停用词
        frequencyAnalyzer.setStopWords(loadStopWords());
        //中文分词模式
        frequencyAnalyzer.setWordTokenizer(new ChineseWordTokenizer());
        //设置trim
        frequencyAnalyzer.addNormalizer(new TrimToEmptyNormalizer());

        final Dimension dimension = new Dimension(option.getHeight(), option.getHeight());
        final WordCloud wordCloud = new WordCloud(dimension, CollisionMode.PIXEL_PERFECT);
        List newTexts = new ArrayList();
        String[] strings = texts.get(0).toString().split("。");
        for (String s : strings) {
            newTexts.add(s);
        }
        final List<WordFrequency> wordFrequencies = frequencyAnalyzer.load(newTexts);

        wordCloud.setPadding(2);
        wordCloud.setKumoFont(new KumoFont(new Font(option.getFont(), Font.PLAIN, defaultFontSize)));
//        wordCloud.setKumoFont(new KumoFont(new Font(defaultFont, Font.PLAIN, defaultFontSize) ));
        wordCloud.setBackgroundColor(option.getBackgroundColor());
        wordCloud.setBackground(new CircleBackground(option.getHeight() / 2));
        wordCloud.setColorPalette(getRamdomColor());
        wordCloud.setFontScalar(new SqrtFontScalar(fontScaleFrom, fontScanleTo));
        wordCloud.build(wordFrequencies);
        wordCloud.writeToFile(filePath);

        File file = new File(filePath);
        return file;

    }

    /**
     * 图片蒙版词云，将在所有不透明像素上绘制字词
     *
     * @param texts
     * @param option
     * @return
     * @throws IOException
     */
    @Override
    public File imageCloud(List texts, WordsCloudOption option) throws IOException {

        logger.info("为text:" + texts.get(0).toString().substring(0, texts.get(0).toString().length() / 10) + "..." + "生成矩形词云");

        final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
        final UrlFilter urlFilter = new UrlFilter();
        final String filePath = getFileSavePath(option.getSavePath());

        frequencyAnalyzer.setWordFrequenciesToReturn(600);
        //设置最小分词长度为
        frequencyAnalyzer.setMinWordLength(option.getMinWordLength());
        //过滤停用词
        frequencyAnalyzer.setStopWords(loadStopWords());
        //中文分词模式
        frequencyAnalyzer.setWordTokenizer(new ChineseWordTokenizer());
        //设置trim
        frequencyAnalyzer.addNormalizer(new TrimToEmptyNormalizer());

        final Dimension dimension = new Dimension(option.getWidth(), option.getHeight());
        final WordCloud wordCloud = new WordCloud(dimension, CollisionMode.PIXEL_PERFECT);


        final List<WordFrequency> wordFrequencies = frequencyAnalyzer.load(texts);


        wordCloud.setPadding(2);
        wordCloud.setBackgroundColor(option.getBackgroundColor());
        wordCloud.setKumoFont(new KumoFont(new Font(option.getFont(), Font.PLAIN, defaultFontSize)));
//        wordCloud.setKumoFont(new KumoFont(new Font(defaultFont, Font.PLAIN, defaultFontSize) ));
        wordCloud.setBackground(new PixelBoundryBackground(option.getBackgroundImage().getAbsolutePath()));
        wordCloud.setColorPalette(getRamdomColor());
        wordCloud.setFontScalar(new LinearFontScalar(fontScaleFrom, fontScanleTo));
        wordCloud.build(wordFrequencies);
        wordCloud.writeToFile(filePath);

        File file = new File(filePath);
        return file;
    }


    /**
     * 矩形的词云
     *
     * @param texts
     * @param option
     * @return
     * @throws IOException
     */
    @Override
    public File RectangleCloud(List texts, WordsCloudOption option) throws IOException {

        logger.info("为text:" + texts.get(0).toString().substring(0, texts.get(0).toString().length() / 10) + "..." + "生成图片词云");

        final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
        final UrlFilter urlFilter = new UrlFilter();
        final String filePath = getFileSavePath(option.getSavePath());

        frequencyAnalyzer.setWordFrequenciesToReturn(600);
        //设置最小分词长度为
        frequencyAnalyzer.setMinWordLength(option.getMinWordLength());
        //过滤停用词
        frequencyAnalyzer.setStopWords(loadStopWords());
        //中文分词模式
        frequencyAnalyzer.setWordTokenizer(new ChineseWordTokenizer());
        //设置trim
        frequencyAnalyzer.addNormalizer(new TrimToEmptyNormalizer());

        final Dimension dimension = new Dimension(option.getWidth(), option.getHeight());
        final WordCloud wordCloud = new WordCloud(dimension, CollisionMode.PIXEL_PERFECT);


        final List<WordFrequency> wordFrequencies = frequencyAnalyzer.load(texts);


        wordCloud.setPadding(2);
        wordCloud.setBackgroundColor(option.getBackgroundColor());
        wordCloud.setKumoFont(new KumoFont(new Font(option.getFont(), Font.PLAIN, defaultFontSize)));
//        wordCloud.setKumoFont(new KumoFont(new Font(defaultFont, Font.PLAIN, defaultFontSize) ));
        wordCloud.setBackground(new RectangleBackground(dimension));
        wordCloud.setColorPalette(getRamdomColor());
        wordCloud.setFontScalar(new SqrtFontScalar(fontScaleFrom, fontScanleTo));
        wordCloud.build(wordFrequencies);
        wordCloud.writeToFile(filePath);

        File file = new File(filePath);
        return file;
    }


    /**
     * 为词云保存到指定路径
     *
     * @param savePath
     * @return
     */
    private String getFileSavePath(String savePath) {

        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String fileName = MD5Util.MD5(System.currentTimeMillis() + new Random().nextInt(1000) + "");
        savePath += fileName + ".png";
        return savePath;

    }

    /**
     * 停用词过滤
     *
     * @return
     */
    private Collection<String> loadStopWords() {

        SegFilter.FilterBuilder builder = new SegFilter.FilterBuilder();
        SegFilter segFilter = builder.enableStopwords(true).build();
        return segFilter.getKeysSet();
    }

    private ColorPalette getRamdomColor() {
        List<ColorPalette> list = new ArrayList<>();
        list.add(new ColorPalette(new Color(0x4055F1), new Color(0x408DF1), new Color(0x40AAF1), new Color(0x40C5F1), new Color(0x40D3F1), new Color(0xFFFFFF)));
        list.add(new ColorPalette(new Color(0x4055F1), new Color(0x408DF1), new Color(0x40AAF1), new Color(0x40C5F1), new Color(0x40D3F1), new Color(0xFFFFFF)));
        list.add(new ColorPalette(Color.RED, Color.GREEN, Color.YELLOW, Color.BLUE));
        list.add(new LinearGradientColorPalette(Color.RED, Color.BLUE, Color.GREEN, 30, 30));
        list.add(new ColorPalette(new Color(0xD5CFFA), new Color(0xBBB1FA), new Color(0x9A8CF5), new Color(0x806EF5)));
        list.add(new ColorPalette(Color.RED, Color.WHITE, new Color(0x008080)/* TEAL */, Color.GREEN));
//        list.add(1, new ColorPalette(new Color(0xFFFFFF), new Color(0xDCDDDE), new Color(0xCCCCCC)));
//        list.add(0, new ColorPalette(new Color(0xABEDFF), new Color(0x82E4FF), new Color(0x55D6FA)));
        Random r = new Random(System.currentTimeMillis());
        int rn = Math.abs(r.nextInt()) % list.size();
        logger.error("随机数" + rn);
        return list.get(rn);

    }


}
